reduce & map

reduce

reduce() 在 Python 的 functools 模块中。它接受两个参数:一个函数和一个可迭代对象(例如列表),然后使用给定的函数将可迭代对象中的元素逐个合并为单个结果。

functools.reduce(function, iterable[, initializer])

其中:

reduce() 函数的典型用途包括对列表中的元素进行累加、计算乘积、找到最大值或最小值等。

需要注意的是,在 Python 3 中,reduce() 函数不再是内置函数,需要从 functools 模块中导入。

from functools import reduce

# 求列表中所有元素的和
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 输出 15

# 将字符串列表中的所有字符串连接起来
strings = ['Hello', ' ', 'world', '!']
concatenated = reduce(lambda x, y: x + y, strings)
print(concatenated)  # 输出 'Hello world!'

map

map() 是 Python 中的另一个内置函数,用于对可迭代对象中的每个元素应用指定的函数,然后返回一个包含结果的迭代器。

map(function, iterable1, iterable2, ...)

其中:

map() 函数将 function 应用于每个传入的可迭代对象中的元素,然后返回一个迭代器,该迭代器包含了将函数应用于每个元素后的结果。

map() 函数常用于将函数应用于列表、元组等可迭代对象的所有元素,以一种简洁的方式进行批量处理。

numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared))  # 输出 [1, 4, 9, 16, 25]

strings = ['apple', 'banana', 'cherry'] uppercased = map(str.upper, strings) print(list(uppercased)) # 输出 ['APPLE', 'BANANA', 'CHERRY']